using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SpeedSearch
{
    public class Database : IDisposable
    {

        public Config Db;

        static Database()
        {
            if (!Directory.Exists(Program.DirData))
                Directory.CreateDirectory(Program.DirData);

            if (!Directory.Exists(Program.DirData))
                Directory.CreateDirectory(Program.DirData);

            if (!File.Exists(Program.DataFile))
            {
                using (var db = new Config())
                {
                    db.WriteXml(Program.DataFile);
                }
            }

            using (var db = new Database())
                db.Check();
        }

        public Database()
        {
            Db = new Config();
            Db.ReadXml(Program.DataFile, System.Data.XmlReadMode.IgnoreSchema);
            Db.Indexes.Columns["DateCreated"].DefaultValue = DateTime.Now;
            Db.Indexes.Columns["Extensions"].DefaultValue = IndexHelper.Extensions;
        }

        public void Save()
        {
            Db.AcceptChanges();
            Db.WriteXml(Program.DataFile);
        }

        public SpeedSearch.Config.ParametersRow Parameters
        {
            get { return Db.Parameters.Count == 0 ? null : Db.Parameters[0]; }
        }

        public SpeedSearch.Config.IndexesDataTable Indexes
        {
            get { return Db.Indexes; }
        }

        public SpeedSearch.Config.DirectoriesDataTable Directories
        {
            get { return Db.Directories; }
        }

        /// <summary>
        /// Checa se os caminhos dos índices existem. Se não existir, tenta mapear para DirIndexes
        /// </summary>
        public void Check()
        {
            bool isChanged = false;
            var pars = Parameters;
            if (Parameters == null)
            {
                var par = Db.Parameters.NewParametersRow();
                par.IndexDirectory = Path.Combine(Program.DirRoot, "Indexes");
                par.Version = Program.DbVersion;
                Db.Parameters.Rows.Add(par);
                isChanged = true;
            }

            if (!Directory.Exists(Parameters.IndexDirectory))
                Directory.CreateDirectory(Parameters.IndexDirectory);

            Program.Db = this;
            foreach (var rowi in Db.Indexes)
            {
                if (rowi.Path == null || !Directory.Exists(rowi.Path))
                {
                    string newPath = Program.GetIndexFile(rowi.IndexName);
                    if (!Directory.Exists(newPath))
                        Directory.CreateDirectory(newPath);
                    rowi.Path = newPath;
                    isChanged = true;

                }

                string ext = SortExtensions(rowi.Extensions);
                if (rowi.Extensions != ext)
                {
                    rowi.Extensions = ext;
                    isChanged = true;
                }
            }

            if (isChanged)
                Save();
        }

        public void Dispose()
        {
            if (Db != null)
                Db.Dispose();
        }

        public static string SortExtensions(string extensions)
        {
            if (string.IsNullOrWhiteSpace(extensions))
                return extensions;

            List<string> exts = extensions.Replace("*.", ".").ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            for (int i = 0; i < exts.Count; i++)
            {
                exts[i] = exts[i].Trim();
                if (!exts[i].StartsWith("."))
                    exts[i] = "." + exts[i];
            }
            exts.Sort();
            return string.Join(", ", exts.ToArray());
        }

    }

}
